const http = require('http')
const fs = require('fs')
const path = require('path')
const url = require('url')
let mime = require('./model/getmimefromfile')


const app = http.createServer((req, res) => {
  let pathname = url.parse(req.url).pathname
  if (pathname === '/') {
    pathname = '/index.html'
  }

  if(pathname !== '/favicon.ico') {
    fs.readFile(`static/${pathname}`, (err, data) => {
      if (err) {
        fs.readFile(`static/404.html`, (error, errData) => {
          res.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'})
          res.write(errData)
          res.end()
        })
      } else {
        let extname = mime.getMime(path.extname(pathname))
        res.writeHead(200, {'Content-Type': `${extname};charset=utf-8`})
        res.write(data)
        res.end()
      }
    })
  }
})

app.listen(8081)